package chat

import (
	"context"
	"time"
	"xr-game-server/core/actor"
	"xr-game-server/core/constants/cmd"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/httpserver"
	"xr-game-server/core/push"
	"xr-game-server/dao/roledao"
	"xr-game-server/dto/chatdto"
	"xr-game-server/errercode"
)

var worldHistory = make([]*chatdto.PushChatDto, common.Zero)
var worldActor = actor.NewActor(1000)

func initWorld() {
	worldActor.Start()
}

func WorldChat(ctx context.Context, req *chatdto.WorldChatReq) (bool, error) {
	roleId := httpserver.GetAuthId(ctx)
	cd := chkCD(roleId, World)
	if cd != nil && time.Now().Before(*cd) {
		return false, errercode.CreateCode(errercode.ChatCD)
	}
	roleData := roledao.GetRoleByRole(roleId)
	pushDto := chatdto.NewPushChatDto(roleData, req.Content, req.Param)
	push.Broadcast(cmd.WorldChat, pushDto)
	flushCD(roleId, World)
	worldActor.Send(pushDto, func(data any) {
		worldHistory = append([]*chatdto.PushChatDto{data.(*chatdto.PushChatDto)}, worldHistory...)
		if len(worldHistory) > WorldMax {
			worldHistory = worldHistory[:WorldMax]
		}
	})
	return true, nil
}

func GetWorldChat(ctx context.Context, req *chatdto.GetWorldChatReq) ([]*chatdto.PushChatDto, error) {
	return worldHistory, nil
}
